package com.sixth.service;

import com.sixth.fign.UserFign;
import com.sixth.entity.Permission;
import com.sixth.entity.User;
import com.sixth.fign.PermissionFeign;
import com.sixth.until.MyUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: self-tui-education
 * @description:
 * @author: 高振杨
 * @create: 2022-04-14 16:41
 **/
@Service(value = "userDetailsService")
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserFign userFign;
    @Autowired
    private PermissionFeign permissionFeign;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户的信息. sso独立的人来写的微服务
        // system也是独立的人来写的微服务 因为在system有关于对数据库user操作。 我们只需要调用system的接口即可
        // 基于restTemplate远程调用  也可以使用openfeign
        //如果使用openfeign的步骤: 1.引入依赖  2.开启openfeign  3.使用openfeign
        User user = userFign.findByUsername(username);

        if(user!=null){
            //为用户赋值权限信息。
            MyUserDetails myUserDetails=new MyUserDetails();
            BeanUtils.copyProperties(user,myUserDetails); //把user对象中对应的属性赋值到MyUserDetails对应的属性上



            //根据用户id查询用户具有的权限。
            List<Permission> permissions = permissionFeign.getPermissionByUserid(user.getId());

            List<GrantedAuthority> authorities = permissions.stream().map(item -> new SimpleGrantedAuthority(item.getPath()))
                    .collect(Collectors.toList());

            myUserDetails.setAuthorities(authorities);//设置用户的权限。


            return myUserDetails;
        }
        return null;
    }
}
